package com.dajingling.dao.impl;

import com.dajingling.bean.Express;
import com.dajingling.bean.UserAdmin;
import com.dajingling.dao.BaseUserAdminDao;
import com.dajingling.exception.DuplicateCodeException;
import com.dajingling.util.DruidUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserAdminDaoMysql  implements BaseUserAdminDao {

    /*
    查询：用户总数量，新增用户总数量，
    select count(uid) size,count(to_days(logontime)=to_days(now()) or null) today from useradmin;
     */
    public static final String SQL_CONSOLE = "select count(uid) size,count(to_days(logontime)=to_days(now()) or null) today from useradmin";
    /*
    查询数据库所有用户信息
     */
    public static final String SQL_FIND_ALL = "select * from useradmin";
    /*
    分页查询数据库所有用户信息
     */
    public static final String SQL_FIND_LIMIT = "select * from useradmin limit ?,?";
    /*
    根据手机号查询数据库用户信息
     */
    public static final String SQL_FIND_BY_USERPHONE = "select * from useradmin where userphone=?";
    /*
    用户录入
    insert into useradmin(username,password,userphone,idcard,logontime) values(?,?,?,?,now())
     */
    public static final String SQL_INSERT = "insert into useradmin(username,password,userphone,idcard,logontime) values(?,?,?,?,now())";
    /*
    用户修改
    update useradmin set username=?,userphone=?,idcard=?,password=? where userphone=?;
     */
    public static final String SQL_UPDATE = "update useradmin set username=?,userphone=?,idcard=?,password=? where userphone=?";
    /*
    用户删除
     */
    public static final String SQL_DELETE = "delete from useradmin where userphone=?";


    /**
     * 查询数据库全部用户（总数，新增）
     *
     * @return {size:总数,day:新增}
     */
    @Override
    public Map<String, Integer> console() {
        Map data = new HashMap();
        //1.获取数据库的连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //2.预编译SQL语句
            statement = connection.prepareStatement(SQL_CONSOLE);
            //3.填充参数（可选）
            //4.执行SQL语句
            resultSet = statement.executeQuery();
            //5.获取执行结果
            if (resultSet.next()){
                int size = resultSet.getInt(1);
                int today = resultSet.getInt(2);
                data.put("data_size",size);
                data.put("data_day",today);
            }
        }catch (Exception e) {
            System.out.println("查询快递数量失败！！！");
        }finally {
            //6.资源的释放
            DruidUtil.close(connection,statement,resultSet);
        }
        return data;
    }

    /**
     * 查询所有用户
     *
     * @param limit      分页：true，查询所有快递：false
     * @param offset     SQL的起始索引
     * @param pageNumber 页查询数量
     * @return 用户列表
     */
    @Override
    public List<UserAdmin> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<UserAdmin> list = new ArrayList();
        //1.获取数据库的连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //2.预编译SQL语句
            if (limit){
                statement = connection.prepareStatement(SQL_FIND_LIMIT);
                //3.填充参数（可选）
                statement.setInt(1,offset);
                statement.setInt(2,pageNumber);
            }else {
                statement = connection.prepareStatement(SQL_FIND_ALL);
            }
            //4.执行SQL语句
            resultSet = statement.executeQuery();
            //5.获取执行结果
            while (resultSet.next()){
                int uid = resultSet.getInt(1);
                String userName = resultSet.getString(2);
                String password = resultSet.getString(3);
                String userPhone = resultSet.getString(4);
                String idCard = resultSet.getString(5);
                Timestamp logonTime = resultSet.getTimestamp(6);
                Timestamp loginTime = resultSet.getTimestamp(7);
                list.add(new UserAdmin(uid, userName, password, userPhone, idCard, logonTime, loginTime,null));
            }
        }catch (Exception e) {
            System.out.println("查询用户列表失败！！！");
        }finally {
            //6.资源的释放
            DruidUtil.close(connection,statement,resultSet);
        }
        return list;
    }

    /**
     * 根据用户的手机号，查询用户信息
     *
     * @param userPhone 电话号码
     * @return 用户类，不存在：null
     */
    @Override
    public UserAdmin findByUserPhone(String userPhone) {
        UserAdmin userAdmin = null;
        //1.获取数据库的连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //2.预编译SQL语句
            statement = connection.prepareStatement(SQL_FIND_BY_USERPHONE);
            //3.填充参数（可选）
            statement.setString(1,userPhone);
            //4.执行SQL语句
            resultSet = statement.executeQuery();
            //5.获取执行结果
            if (resultSet.next()){
                int uid = resultSet.getInt(1);
                String userName = resultSet.getString(2);
                String password = resultSet.getString(3);
                String idCard = resultSet.getString(5);
                Timestamp logonTime = resultSet.getTimestamp(6);
                Timestamp loginTime = resultSet.getTimestamp(7);
                userAdmin = new UserAdmin(uid, userName, password, userPhone, idCard, logonTime, loginTime,null);
            }
        }catch (Exception e) {
            System.out.println("查询用户信息失败！！！");
        }finally {
            //6.资源的释放
            DruidUtil.close(connection,statement,resultSet);
        }
        return userAdmin;
    }

    /**
     * 用户录入
     *
     * @param userAdmin 要录入的用户对象
     * @return true，false
     */
    @Override
    public boolean insert(UserAdmin userAdmin) {
        //1.连接的获取
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        try {
            //2.预编译SQL语句
            statement = connection.prepareStatement(SQL_INSERT);
            //3.填充参数
            //insert into useradmin(username,password,userphone,idcard,logontime) values(?,?,?,?,now())
            statement.setString(1,userAdmin.getUserName());
            statement.setString(2,userAdmin.getPassword());
            statement.setString(3,userAdmin.getUserPhone());
            statement.setString(4,userAdmin.getIdCard());
            //4.执行SQL语句，并获取执行结果
            return statement.executeUpdate()>0;
        } catch (SQLException e1) {
            System.out.println("用户录入失败！");
        }finally {
            //5.释放资源
            DruidUtil.close(connection,statement,null);
        }
        return false;
    }

    /**
     * 根据电话，用户信息修改
     *
     * @param userPhone    用户号码
     * @param newUserAdmin 新的用户对象（username，password，userPhone，idcard）
     * @return true，false
     */
    @Override
    public boolean update(String userPhone, UserAdmin newUserAdmin) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(SQL_UPDATE);
            //update useradmin set username=?,userphone=?,idcard=?,password=? where userphone=?
            statement.setString(1,newUserAdmin.getUserName());
            statement.setString(2,newUserAdmin.getUserPhone());
            statement.setString(3,newUserAdmin.getIdCard());
            statement.setString(4,newUserAdmin.getPassword());
            statement.setString(5,userPhone);
            return statement.executeUpdate()>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection,statement,null);
        }
        return false;
    }

    /**
     * 根据userPhone，用户删除
     *
     * @param userPhone 用户手机号
     * @return true，false
     */
    @Override
    public boolean delete(String userPhone) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(SQL_DELETE);
            statement.setString(1,userPhone);
            return statement.executeUpdate()>0?true:false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection,statement,null);
        }
        return false;
    }
}
